package org.penguin.study.bk.dict.controller;

import lombok.extern.slf4j.Slf4j;
import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.dict.entity.SysDictItem;
import org.penguin.study.bk.dict.service.SysDictItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;

/**
 * @author chengyinghua
 */
@Slf4j
@RestController
@RequestMapping("/sys/dictItem")
public class SysDictItemController {

    @Autowired
    private SysDictItemService sysDictItemService;

    /**
     * @return
     * @功能：新增
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysDictItem> add(@RequestBody SysDictItem sysDictItem) {
        Result<SysDictItem> result = new Result<>();
        try {
            sysDictItem.setCreatedTime(new Date());
            sysDictItemService.save(sysDictItem);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * @param sysDictItem
     * @return
     * @功能：编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<SysDictItem> edit(@RequestBody SysDictItem sysDictItem) {
        Result<SysDictItem> result = new Result<>();
        SysDictItem sysdict = sysDictItemService.getById(sysDictItem.getId());
        if (sysdict == null) {
            result.error500("未找到对应实体");
        } else {
            sysDictItem.setUpdatedTime(new Date());
            sysDictItemService.updateById(sysDictItem);
            result.success("编辑成功!");
        }
        return result;
    }

    /**
     * @param id
     * @return
     * @功能：删除字典数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<SysDictItem> delete(@RequestParam(name = "id") String id) {
        Result<SysDictItem> result = new Result<>();
        SysDictItem joinSystem = sysDictItemService.getById(id);
        if (joinSystem == null) {
            result.error500("未找到对应实体");
        } else {
            sysDictItemService.removeById(id);
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * @param ids
     * @return
     * @功能：批量删除字典数据
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<SysDictItem> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<SysDictItem> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sysDictItemService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }
}
